﻿using CBS.APP;
using CBS.DB.CBSEntity;
using CBS.Desktop.FormPage;
using CBS.Model.ManageModel;
using CBS.Model.UIModel;
using CBS.Model.ViewModel;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CBS.Desktop.ViewPartial
{
    /// <summary>
    /// StudentSignup.xaml 的交互逻辑
    /// </summary>
    public partial class StudentSignUp : UserControl
    {
        public Pagination pager = new Pagination() { rows = 10, page = 1, sidx = nameof(StudentSignUpViewModel.StudentId), sord = "desc" };
        public StudentSignUp()
        {
            InitializeComponent();

            LoadCondation();
        }

        private void UserControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                // 调用处理方法
                pager.page = 1;
                pg_DataList.PageIndex = 1;
                FlushGrid();
                e.Handled = true; // 如果需要，标记事件已处理
            }
        }
        private async void LoadCondation()
        {
            btn_Import.IsEnabled = false;
            btn_Search.IsEnabled = false;
            btn_Add.IsEnabled = false;
            btn_Delete.IsEnabled = false;
            btn_ExportBatchSignInTemplate.IsEnabled = false;

            // 加载 ComboBox 数据
            await LoadDataAsync();

            // 查询 Grid 数据
            //FlushGrid();

            btn_Import.IsEnabled = true;
            btn_Search.IsEnabled = true;
            btn_Add.IsEnabled = true;
            btn_Delete.IsEnabled = true;
            btn_ExportBatchSignInTemplate.IsEnabled = true;
        }

        private async Task LoadDataAsync()
        {
            // 使用 Task.WhenAll 等待所有 ComboBox 数据加载完成
            var tasks = new List<Task>
            {
                BindSemester(),
                BindGrade(),
                BindClass(),
                BindCourse(),
            };

            await Task.WhenAll(tasks);
        }

        private async Task BindSemester()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => SemesterApp.GetSelectList());

                if (list.Count == 0)
                {
                    return;
                }


                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Semester.ItemsSource = list;
                }));
                cb_Semester.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async Task BindGrade()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => GradeApp.GetSelectList());

                list.Insert(0, new GradeViewModel { GradeId = 0, GradeName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Grade.ItemsSource = list;
                }));
                cb_Grade.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindClass()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => ClassApp.GetSelectList());

                list.Insert(0, new ClassViewModel { ClassId = 0, ClassName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Class.ItemsSource = list;
                }));
                cb_Class.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindCourse()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => CourseApp.GetSelectList());

                list.Insert(0, new CourseViewModel { CourseId = 0, CourseName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Course.ItemsSource = list;
                }));
                cb_Course.SelectedIndex = 0;

            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void FlushGrid()
        {
            try
            {
                btn_Search.IsEnabled = false;

                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;
                string key = tb_SearchKey.Text.Trim();

                var data = await Task.Run(() => StudentSignUpApp.GetList(pager, semesterId, gradeId, classId, courseId, key));

                this.Dispatcher.Invoke(() =>
                {
                    pg_DataList.MaxPageCount = pager.total;
                    dgr_DataList.ItemsSource = data;
                    btn_Search.IsEnabled = true;
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void btn_Import_Click(object sender, RoutedEventArgs e)
        {
            ImportStudentSignUpInfo import = new()
            {
                Owner = Window.GetWindow(this),
            };

            var result = import.ShowDialog();
            if (result.HasValue && result.Value)
            {
                pager.page = 1;
                pg_DataList.PageIndex = 1;
                FlushGrid();
            }
        }

        private void btn_Add_Click(object sender, RoutedEventArgs e)
        {
            AddStudentSignUp signUp = new()
            {
                Owner = Window.GetWindow(this),
            };

            var result = signUp.ShowDialog();
            if (result.HasValue && result.Value)
            {
                pager.page = 1;
                pg_DataList.PageIndex = 1;
                FlushGrid();
            }
        }

        private void btn_Delete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;
                string key = tb_SearchKey.Text.Trim();
                if (StudentSignUpApp.BatchDeleteSignUp(semesterId, gradeId, classId, courseId, key))
                {
                    FlushGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void btn_Search_Click(object sender, RoutedEventArgs e)
        {
            pager.page = 1;
            pg_DataList.PageIndex = 1;
            FlushGrid();
        }

        private void dg_Delete(object sender, RoutedEventArgs e)
        {
            try
            {
                var tmp = sender as System.Windows.Controls.Button;
                var data = tmp.DataContext as StudentSignUpViewModel;
                if (StudentSignUpApp.DeleteStudentSignUp(data.StudentId, data.CoursePlanId))
                {
                    FlushGrid();
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void pg_DataList_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            pager.page = e.Info;
            FlushGrid();
        }

        private void btn_ExportBatchSignInTemplate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                btn_ExportBatchSignInTemplate.IsEnabled = false;
                Mouse.OverrideCursor = Cursors.Wait;

                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;
                string key = tb_SearchKey.Text.Trim();




                Mouse.OverrideCursor = null;

            }
            catch (Exception ex)
            {
                Mouse.OverrideCursor = null;
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void dgr_DataList_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            // 设置行头为行号（从1开始）
            e.Row.Header = (e.Row.GetIndex() + 1).ToString();
        }
    }
}
